package com.zhupanlin.filter;

import com.zhupanlin.exception.KaptchNotMatchException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: 自定义验证码的 filter
 * @date 2024/12/15 22:29
 */
public class KaptchFilter extends UsernamePasswordAuthenticationFilter {

    private static final String FORM_KAPTCHA_KEY = "kaptcha";
    private String kaptchaParameter = FORM_KAPTCHA_KEY;

    public String getKaptchaParameter() {
        return kaptchaParameter;
    }

    public void setKaptchaParameter(String kaptchaParameter) {
        this.kaptchaParameter = kaptchaParameter;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 1.从请求中获取验证码
        // 2.与 session 中的验证码进行比较
        String verifyCode = request.getParameter(kaptchaParameter);
        String kaptcha = (String) request.getSession().getAttribute("kaptcha");
        if (!ObjectUtils.isEmpty(verifyCode) && !ObjectUtils.isEmpty(kaptcha) &&
            verifyCode.equalsIgnoreCase(kaptcha)) {
            return super.attemptAuthentication(request, response);
        }
        throw new KaptchNotMatchException("验证码错误!");
    }
}
